package inet.app;

import inet.app.controller.gcm.CommonUtilities;
import inet.app.model.util.MyPreferenceManager;
import inet.app.model.util.StringTool;
import inet.app.model.util.Util;
import inet.app.view.activity.FlashScreen;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gcm.GCMBaseIntentService;
import com.google.android.gcm.GCMRegistrar;

public class GCMIntentService extends GCMBaseIntentService {
	private static AsyncTask<Void, Void, Void> mRegisterTask;
	private static String deviceId = "", numberphone = "";

	public GCMIntentService() {
		super(CommonUtilities.SENDER_ID);
		Log.d(TAG, "GCMIntentService init");
	}

	@Override
	protected void onMessage(Context ctx, Intent intent) {

		Log.d(TAG, "Message Received");
		String message = StringTool.DecodeBase64(intent
				.getStringExtra("message"));
		System.out.println("TIN NHẮN NHẬN DC  " + message);
		CommonUtilities.displayMessage(ctx, deviceId);
		sendGCMIntent(ctx, message);
		if(message.contains("FREE")){
			MyPreferenceManager.getInstance(getApplicationContext()).setFree(false);
		}else if (message.contains("MONEY")) {
			MyPreferenceManager.getInstance(getApplicationContext()).setFree(false);
		}else if((Util.finishLiveMB()&&Util.getPreferences("ONLIVEMB", getApplicationContext())==true)
		||(Util.finishLiveMT()&&Util.getPreferences("ONLIVEMT", getApplicationContext())==true)
		||(Util.finishLiveMN()&&Util.getPreferences("ONLIVEMN", getApplicationContext())==true))
			System.out.println("NOT SHOW NOTIFY");
		else
			generateNotification(ctx,Util.getPreferences("quit", getApplicationContext()),message);
	}

	@Override
	protected void onRegistered(Context ctx, String regId) {
		Log.d(TAG, regId);
		registered(ctx, CommonUtilities.appName);
	}

	@Override
	protected void onUnregistered(Context ctx, String regId) {
		Log.i(TAG, "Device unregistered");
		CommonUtilities.displayMessage(ctx, "gcm_unregistered");
		unregistered(ctx, regId);
	}

	@Override
	protected void onError(Context ctx, String sError) {
		// TODO Auto-generated method stub
		Log.d(TAG, "Error: " + sError);
	}

	public void sendGCMIntent(Context ctx, String message) {
		Intent broadcastIntent = new Intent();
		broadcastIntent.setAction("GCM_RECEIVED_ACTION");
		broadcastIntent.putExtra("gcm", message);
		ctx.sendBroadcast(broadcastIntent);
	}

	public static void registered(final Context context, final String appName) {
		try {
			// -----------------------------------GET DEVICE FROM
			// DT--------------//
			GCMRegistrar.checkDevice(context);
			GCMRegistrar.checkManifest(context);
			deviceId = GCMRegistrar.getRegistrationId(context);

			numberphone = getMyPhoneNumber(context);
			System.out.println("IDA MAY " + deviceId);
//			Toast.makeText(context, "ID máy " + deviceId, Toast.LENGTH_LONG)
//					.show();
			// ------------------------------------------------END----------------//
			if (deviceId.equals("")) {
				GCMRegistrar.register(context, CommonUtilities.SENDER_ID);
				deviceId = GCMRegistrar.getRegistrationId(context);
			} else {
				if (GCMRegistrar.isRegisteredOnServer(context)) {
					Toast.makeText(context.getApplicationContext(),
							"Already registered with GCM", Toast.LENGTH_LONG)
							.show();
				} else {
					mRegisterTask = new AsyncTask<Void, Void, Void>() {
						@Override
						protected Void doInBackground(Void... params) {
							// Register on our server // On server creates a new
							// user
							try {
								GCMIntentService.sendRegistrationToServer(
										deviceId, appName, numberphone);
							} catch (IOException e) {
								e.printStackTrace();
							}
							return null;
						}

						@Override
						protected void onPostExecute(Void result) {
							mRegisterTask = null;
						}
					};
					mRegisterTask.execute(null, null, null);
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		Log.d(TAG, deviceId);

	}

	public static void sendRegistrationToServer(String deviceId,
			String appName, String numberPhone) throws IOException {
		try {
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost(CommonUtilities.SERVER_URL);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("deviceid", deviceId));
			params.add(new BasicNameValuePair("appname", appName));
			params.add(new BasicNameValuePair("numberphone", numberPhone));
			UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,
					HTTP.UTF_8);
			post.setEntity(ent);
			HttpResponse responsePOST = client.execute(post);
			HttpEntity resEntity = responsePOST.getEntity();
			if (resEntity != null) {
				Log.i("RESPONSE", EntityUtils.toString(resEntity));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void unregistered(final Context context, final String regId) {
	        String serverUrl = CommonUtilities.SERVER_URL + "/unregister";
	        Map<String, String> params = new HashMap<String, String>();
	        params.put("regId", regId);
	        try {
	            post(serverUrl, params);
	            GCMRegistrar.setRegisteredOnServer(context, false);
	            String message = "server_unregistered";
	            CommonUtilities.displayMessage(context, message);
	        } catch (IOException e) {
	            String message = "server_unregister_error";
	            CommonUtilities.displayMessage(context, message);
	        }
	        
	    }
	 
		public static void post(String endpoint, Map<String, String> params)
	            throws IOException {    
	        URL url;
	        try {
	            url = new URL(endpoint);
	        } catch (MalformedURLException e) {
	            throw new IllegalArgumentException("invalid url: " + endpoint);
	        }
	        StringBuilder bodyBuilder = new StringBuilder();
	        Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
	        // constructs the POST body using the parameters
	        while (iterator.hasNext()) {
	            Entry<String, String> param = iterator.next();
	            bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
	            
	            if (iterator.hasNext()) {
	            	bodyBuilder.append('&');
	            }
	        }
	        String body = bodyBuilder.toString();
	        byte[] bytes = body.getBytes();
	        HttpURLConnection conn = null;
	        try {
	            Log.e("URL", "> " + url);
	            conn = (HttpURLConnection) url.openConnection();
	            conn.setDoOutput(true);
	            conn.setUseCaches(false);
	            conn.setFixedLengthStreamingMode(bytes.length);
	            conn.setRequestMethod("POST");
	            conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
	            OutputStream out = conn.getOutputStream();
	            out.write(bytes);
	            out.close();
	            // handle the response
	            int status = conn.getResponseCode();
	            if (status != 200) {
	              throw new IOException("Post failed with error code " + status);
	            }
	        } finally {
	            if (conn != null) {
	                conn.disconnect();
	            }
	        }
	      }
	    
	    public static void generateNotification(Context context,boolean quit, String message) {
	        CharSequence contentTitle = message.split("-")[0];
			Notification notifyDetails = new Notification(R.drawable.icon_kqxs, message.split("-")[1],System.currentTimeMillis());
			CharSequence contentText = message.split("-")[1];
			Intent notifyIntent = null;
			if (quit) {
				 notifyIntent=  new Intent(context,FlashScreen.class);
			}else {
				 notifyIntent=  new Intent();
			}
			PendingIntent intent = PendingIntent.getActivity(context, 0, notifyIntent,android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
			notifyDetails.setLatestEventInfo(context,contentTitle, contentText, intent);
			notifyDetails.flags |= Notification.FLAG_AUTO_CANCEL;
			notifyDetails.defaults |= Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE;
//			notifyDetails.defaults |= Notification.DEFAULT_VIBRATE;
			NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
			mNotificationManager.notify(0, notifyDetails);
	    }
		public static String getMyPhoneNumber(Context context){
		    return ((TelephonyManager) context.getSystemService(TELEPHONY_SERVICE)).getLine1Number();
		}

	}
